package com.showsu.editor.utils.remote;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.HttpClientUtil;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: https://app.socialscrape.com/login
 * @Date: Created in 2:29 下午 2024/1/13
 * @Modified By:
 */
@Slf4j
@Component
public class SocialscrapeUtil {

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    private static final Integer pageSize = 20;
    private static final Integer totalLimit = 60;

    @Value("${socialscrapeAPI.url}")
    private String baseUrl;

    @Value("${socialscrapeAPI.token}")
    private String token;

    private static final String jsonHeader = "application/json";

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情
     * https://docs.socialscrape.com/reference/note-comments-copy
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<XhsAwemeDetailResult>(){}.getType();
        Gson gson = new Gson();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        //组装请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("X-Api-Key", token);
        headers.put("accept", jsonHeader);

        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    String responseInner = HttpClientUtil.get(baseUrl + "/v3/xhs/get-note-data?noteId=" + noteId,
                            null, headers, null, null);
                    log.info("SocialscrapeUtil查询xhs作品详情-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    XhsAwemeDetailResult temp = gson.fromJson(responseInner, type);
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("SocialscrapeUtil.getXhsAwemeDetail(String) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        try {
            result = gson.fromJson(response, type);
        } catch (Exception e) {
            log.error("SocialscrapeUtil.getXhsAwemeDetail(String) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-Api-Key", "cf12a0ce-7a28-41ff-b6e6-1b3684ee2f19");
        headers.put("accept", "application/json");

        String response = HttpClientUtil.get("https://api.socialscrape.com/v3/xhs/get-note-data?noteId=660a8f2b000000001b00fd70",
                null, headers, null, null);
        System.out.println(response);
    }
}
